﻿using System;
using System.Collections.Generic;
using BotonJXC.Entity;
using AccountDAO = BotonJXC.DAO.AccountDAO;
using BotonJXC.Util;
using NHibernate.Criterion;

namespace BotonJXC.BLL
{
    public class AccountBLL : BaseBLL<AccountDAO, Account, int>
    {
        SysLogBLL _sysLogBll = new SysLogBLL();
        public AccountBLL()
        {
        }

        public PageModel<Account> Find(string username, string realname, int depId, int roleId, int start, int count)
        {
            List<ICriterion> criterions = new List<ICriterion>();
            if (!string.IsNullOrEmpty(username))
            {
                criterions.Add(Restrictions.Eq("Username", username));
            }
            if (!string.IsNullOrEmpty(realname))
            {
                criterions.Add(Restrictions.Like("Realname", realname, MatchMode.Anywhere));
            }
            if (depId > 0)
            {
                criterions.Add(Restrictions.Eq("Department.DepId", depId));
            }
            if (roleId > 0)
            {
                criterions.Add(Restrictions.Eq("Role.RoleId", roleId));
            }
            return Dao.FindByPage(criterions.ToArray(), null, start, count);
        }

        public Account CheckLogin(string username, string password)
        {
            Account acc = Dao.GetByUsername(username);
            if (acc != null)
            {
                if (acc.Password.Equals(Encoder.MD5(password)) && "Y".Equals(acc.Enabled))
                {
                    SysLog log = new SysLog();
                    log.Operater = acc;
                    log.OperaterName = acc.Realname;
                    log.OperateTime = DateTime.Now;
                    log.OperateType = 1;
                    log.IP = Utils.GetLocalIpV4();
                    _sysLogBll.Save(log);
                }
                else
                {
                    return null;
                }
            }
            return acc;
        }
    }
}